<?php
 
	function smarty_block_purchases($params, $content, &$smarty, &$repeat) {

		global $db, $config, $counter;

		$l = count($smarty->_tag_stack);
		if(empty($params['name'])) $params['name'] = "purchases";

		if(empty($smarty->blockvars[$l])) {
			$sqlstr = "select * from {$config->db_prefix}purchases where 1=1";
			if (!empty($params['id'])) $sqlstr .= " and id = ".$db->qstr($params['id']);
			if (!empty($params['productid'])) $sqlstr .= " and productid = ".$db->qstr($params['productid']);
			if (!empty($params['shopid'])) $sqlstr .= " and shopid = ".$db->qstr($params['shopid']);
			if (!empty($params['keywords'])) $sqlstr .= " and (productid=". $db->qstr($params['keywords']) ." or product like ". $db->qstr("%".$params['keywords']."%") .")";
			if (!empty($params['sdate'])) $sqlstr .= " and thedate>=". strtotime($params['sdate']);
			if (!empty($params['edate'])) $sqlstr .= " and thedate<=". strtotime($params['edate']);
			if (!empty($params['cond'])) $sqlstr .= " and ({$params['cond']})";
			
			if (!empty($params['counter'])) $counter = $db->getrow(str_replace("*", "sum(number) number, sum(pricebuy*number) price", $sqlstr));
			if (!empty($params['order'])) $sqlstr .= " order by {$params['order']}";

			$limit = empty($params['limit'])?9999:$params['limit'];
			$page = empty($params['page'])?1:$params['page'];
			$pager = new pager($limit, $page);
			$smarty->blockvars[$l] = $pager->execute($db, $sqlstr);

			//
			if(!$smarty->blockvars[$l]) return $repeat = false;
			if(!empty($params['pager'])) $smarty->assign($params['pager'], $pager);
		}
	
		if(list($key, $item) = each($smarty->blockvars[$l])) {
			$repeat = true;
			if(!empty($counter)) $item["counter"] = $counter;
			$smarty->assign($params['name'], $item);
		}
		else {
			$repeat = false;
			$counter = "";
			reset($smarty->blockvars[$l]);
		}
		
		if(!is_null($content)) print $content;
	
		//
		if(!$repeat) $smarty->blockvars[$l] = array();
	}

?>